<?php
namespace App\Http\Controllers\Api\Card;

use DB;

use Carbon\Carbon;

use Illuminate\Http\Request;

use App\Service\CardService;

use App\Service\WdhService;

use App\Models\Wx\WxCustomer;//微信粉丝表

use App\Models\Card\CardCoupon;//卡券表

use App\Models\Card\CardCouponBuyLog;//卡券购买记录表

use App\Http\Controllers\Controller;

use App\Models\Mall\MallMaster;//门店表

use App\Models\Pay\SysPaytype;//支付方式表

use App\Models\Deliver\Deliver;//地址表

use App\Models\Card\CardCouponCode;//活动码池表

use App\Models\Customer\Customer; //会员表

use App\Models\ConfigureFunction; //设置表

use App\Service\Pay\WxPayService;

use Illuminate\Support\Facades\Redis as Redis;

class CheckoutController extends Controller
{

    /**
     * 券中心结算页
     * @param Request $request
     * @return array
     */
    public function checkout(Request $request)
    {
        $host = $request->getSchemeAndHttpHost();
        $uid = $request->input('uid');
        $session_id = $request->input('session_id');
        if ( empty($uid) ) {
            return response()->json(['code'=>100001,'message'=>'缺少参数：uid']);
        }

        if ( empty($session_id) ) {
            return response()->json(['code'=>100002,'message'=>'缺少参数：session_id']);
        }

        //获取客户号
        $pcustID = 0;
        $wx_applet_info = Redis::get('WX_APPLET_USER_' .$session_id);
        if ( $wx_applet_info ) {
            $wx_applet_info =  json_decode($wx_applet_info, true);
            if (isset($wx_applet_info['pcustID']) && ebsig_is_int($wx_applet_info['pcustID'])) {
                $pcustID = $wx_applet_info['pcustID'];
            }
        }

        if ($pcustID <= 0) {
            return response()->json(['code' => 100003, 'message' => '请先登录']);
        }

        // 查询会员是否存在
        $cust_master = Customer::find($pcustID);
        if ( !$cust_master ) {
            return response()->json(['code'=>100004,'message'=>'会员信息不存在']);
        }

        //查询字段
        $fields = array('card_id','card_name','card_pic','card_type','time_type','end_time','discount','amount','limit_money','salePrice','useFlg','description',
            'repeat_count','merchantName','get_way','pointsPrice','moneyPrice');

        //查询卡券信息
        $card_coupon = CardCoupon::select($fields)->where('uuid',$uid)->first();
        if ( !$card_coupon ) {
            return response()->json(['code'=>100003,'message'=>'卡券信息不存在']);
        }

        //转换为数组
        $card_coupon = collect($card_coupon)->toArray();

        if ( $card_coupon['useFlg'] == 0 ) {
            return response()->json(['code'=>100003,'message'=>'卡券已禁用']);
        }

        if ( $card_coupon['card_type'] == 2 ) {
            $card_coupon['discount'] = $card_coupon['discount'] * 10;
        }

        // 查询账户积分
        $args_data = array(
            'cardNo' => $cust_master['cardNo'],
            'pcustID' => $cust_master['pcustID'],
            'custID' => $cust_master['custID'],
            'openId' => $cust_master['custID'],
            'mobile'=>$cust_master['custID']
        );

        //查询微信粉丝信息
        $wx_data = WxCustomer::getCache($pcustID);
        if ( $wx_data ){
            $args_data['openId'] = isset($wx_data['openId']) ? $wx_data['openId'] : '';
            $nickName = isset($wx_data['nickName']) ? $wx_data['nickName'] : '';
            $headPic = isset($wx_data['headPic']) ? $wx_data['headPic'] : '';
        }

        //查询账户积分
        $points = WdhService::points( $args_data );

        $card_coupon['limit_money'] = intval($card_coupon['limit_money']);
        $card_coupon['amount'] = intval($card_coupon['amount']);

        $card_coupon['effective_time'] = date('Y.m.d',strtotime($card_coupon['end_time']));

        if ( $card_coupon['repeat_count'] > 0 ) {

            //查询用户领取卡券次数
            $get_card_data = CardCouponCode::where([['activity_id',$card_coupon['card_id']],['pcustID',$pcustID]])->count();
            if ( $get_card_data > 0 ) {
                if ($card_coupon['repeat_count'] <= $get_card_data ){
                    $card_coupon['repeat_count'] = 10000;
                } else {
                    $card_coupon['repeat_count'] = $card_coupon['repeat_count'] - $get_card_data ;
                }
            }
        }

        //查询选店信息
        $shop_id = Redis::get('G_CHOOSE_MALL_ID');
        $mall_data = array();
        $mallareaID = 0;

        //查询支付设置
        $pay_configure = ConfigureFunction::getConfigure(9);
        if ( isset($pay_configure['is_open_mall_area_pay']) && $pay_configure['is_open_mall_area_pay'] > 0  ){
            if ( $shop_id ) {

                $mall_data = MallMaster::select('mallID','mallName','provinceName','cityName','countyName','address','mallareaID')->where('mallID',$shop_id)->first();
                if ( $mall_data ) {
                    $mall_data = collect($mall_data)->toArray();
                }
            }
        }

        //微信支付方式类型
        $wechat_pay_type =  isset($pay_configure['wechat_pay_type']) ? $pay_configure['wechat_pay_type'] : 1 ;

        //查询在线支付方式列表
        $online_data = SysPaytype::where(['payTypeID'=>50])->get()->toArray();
        if ( !$online_data ) {
            return response()->json(['code'=>100003,'message'=>'无支付方式']);
        }

        $online_data[0]['logo_img'] = $host . $online_data[0]['logo_img'];
        
        //余额
        $balance = WdhService::balance( $args_data );

        //查询积分设置
        $points_configure = ConfigureFunction::getConfigure(2);
        $points_exchange_ratio = isset($points_configure['points_exchange_ratio']) ? $points_configure['points_exchange_ratio'] : 100 ;

        //查询会员收货地址
        $deliver_data = Deliver::where([['pcustID',$pcustID],['mallID',$shop_id]])->get()->toArray();
        if ( $deliver_data ) {
            $deliver_name = $deliver_data[0]['custName'];
            $deliver_mobile = $deliver_data[0]['mobile'];
        }

        //返回数据
        $return_data = [
            'coupon' => $card_coupon,//卡券信息
            'nickName' => isset($nickName) ? $nickName : '',
            'headPic' => isset($headPic) ? $headPic : '',
            'points' => $points ,
            'balance' => $balance ,
            'mall' => $mall_data,
            'wechat_pay_type' => $wechat_pay_type , //微信支付方式类型
            'online_pay' => $online_data,//支付方式
            'points_ratio' => $points_exchange_ratio,
            'deliver_name' => isset($deliver_name) ? $deliver_name : '',
            'deliver_mobile' => isset($deliver_mobile) ? $deliver_mobile : '',
        ];

        return response()->json(['code'=>200,'message'=>'ok','data'=>$return_data]);

    }


    /**
     * 购买卡券
     * @param Request $request
     * @return array
     * @throws \Exception
     */
    public function couponsBuy( Request $request )
    {

        $args_data = $request->all();
        $platform = $request->input('platform',6);
        $session_id = $request->input('session_id',session_id());

        if( !isset($args_data['points']) || !isset($args_data['balance']) || !isset($args_data['money']) || !isset($args_data['card_id']) || !isset($args_data['card_num'])
            || !isset($args_data['mallID']) || !ebsig_is_int($args_data['mallID']) || !ebsig_is_int($args_data['card_id']) || !ebsig_is_int( $args_data['card_num'] ) ){
            return response()->json(['code' => 100001, 'message' => '参数错误']);
        }

        if( $args_data['money'] > 0 ){

            if (!isset($args_data['pay_id']) || !ebsig_is_int($args_data['pay_id'])) {
                return response()->json(['code' => 100002, 'message' => '缺少支付方式ID']);
            }

        }

        if ( empty($session_id) ) {
            return response()->json(['code'=>100003,'message'=>'缺少参数：session_id']);
        }

        //获取客户号
        $pcustID = get_customer_id($session_id, $platform);

        $cust_info = Customer::where('pcustID' , $pcustID)->first()->toArray();

        if( empty( $cust_info ) ){
            return response()->json(['code'=>100004,'message'=>'会员信息不存在']);
        }

        $card_data = CardCoupon::where('card_id' , $args_data['card_id'])->first()->toArray();

        if( empty( $card_data ) ){
            return response()->json(['code'=>100004,'message'=>'卡券信息不存在']);
        }

        if( ($args_data['card_num'] + $card_data['getNum']) > $card_data['total_num'] ){
            return response()->json(['code'=>100005,'message'=>'卡券余量不足']);
        }

        $get_amount = CardCouponCode::where([['activity_id',$args_data['card_id']],['pcustID',$pcustID]])->count();

        if( $get_amount > 0 ){
            if( $card_data['repeat_count'] <= $get_amount ){
                return response()->json(['code'=>100006,'message'=>'您已到达领取上限！']);
            }
            if( $card_data['repeat_count'] < ($get_amount + $args_data['card_num']) ){
                return response()->json(['code'=>100007,'message'=>'超过限购数量，请重新填写！']);
            }
        }else{
            if( $card_data['repeat_count'] <  $args_data['card_num'] ){
                return response()->json(['code'=>100008,'message'=>'超过限购数量，请重新填写！']);
            }
        }

        $custPointsSet = ConfigureFunction::getConfigure(2);

        $exchange_rate = 100;
        if( isset($custPointsSet['points_exchange_ratio']) ){
            $exchange_rate = $custPointsSet['points_exchange_ratio'];
        }

        //获取openId
        $openId = '';
        $customer_redis = json_decode(app('redis')->get('WX_APPLET_USER_' . $session_id), true);
        if (isset($customer_redis['openId']) && !empty($customer_redis['openId'])) {
            $openId = $customer_redis['openId'];
        }

        $args_array = array(
            'pcustID' => $pcustID,
            'cardNo' => $cust_info['cardNo'],
            'openId' => $openId
        );

        $points = 0;

        if( $args_data['points'] > 0 ){

            //查询账户积分
            $cust_points = WdhService::points( $args_array );

            if ( $cust_points < 0 || $cust_points < $args_data['points']) {
                return response()->json(['code' => 100009, 'message' => '没有足够的积分可用']);
            }
            $points = $args_data['points'];
        }

        $pointsPrice = $points / $exchange_rate;

        $balance = 0;

        if( $args_data['balance'] > 0 ){

            $cust_balance = WdhService::balance($args_array);

            if( $cust_balance < 0 || $cust_balance < $args_data['balance'] ){
                return response()->json(['code' => 100009, 'message' => '没有足够的余额可用']);
            }

            $balance = $args_data['balance'];
        }

        //应付金额
        $pay_money = ((float)($card_data['pointsPrice'] / $exchange_rate) + $card_data['moneyPrice']) * $args_data['card_num'];

        //实际支付金额
        $total_money = (float)$pointsPrice + $balance + $args_data['money'];

        if( (int)$pay_money != (int)$total_money ){
            return response()->json(['code' => 100006, 'message' => '付款金额小于应付金额']);
        }

        try {

            DB::beginTransaction();

            $bill_no = generate_seqno('seqno_bill', '1', true);

            if( $points > 0 ){

                //扣减积分
                $points_data = array(
                    'pcustID' => $pcustID,
                    'custID' => $cust_info['custID'],
                    'cardNo' => $cust_info['cardNo'],
                    'openId' =>$openId,
                    'points' => $points,
                    'remark' => '订单' . $bill_no . '消费积分'
                );

                $result_array = WdhService::deductionPoints($points_data);
                if ( $result_array['code'] != 200 ) {
                    throw new \Exception($result_array['message'], 400);
                }

            }

            //扣减余额
            if ( $balance > 0 ) {
                $balance_data = array(
                    'cardNo' =>  $cust_info['cardNo'],
                    'pcustID' => $pcustID,
                    'custID' => $cust_info['custID'],
                    'openId' =>$openId,
                    'amount' => $balance,
                    'password' => isset($args_data['payPwd']) ? $args_data['payPwd'] : '',
                    'remark' => '订单' . $bill_no . '扣减'
                );

                $result_array = WdhService::deductionBalance($balance_data);
                if ( $result_array['code'] != 200 ) {
                    throw new \Exception($result_array['message'], 400);
                }
            }

            $result_array['pay'] = array();

            if( $args_data['money'] > 0 ){

                $trade_type = '';
                $wx_config_seeting = ConfigureFunction::getConfigureField(41,'wechat_type');
                if ( $wx_config_seeting == 1) {
                    $trade_type = 'JSAPI';
                }
                if ( $wx_config_seeting != 1 ) {
                    $trade_type = 'NATIVE';
                }

                //微信异步接收路径
                $notify_url = $request->getSchemeAndHttpHost() . '/onlinepay/weixin/notify';

                $params = [
                    'out_trade_no' => $bill_no,
                    'trade_type' => $trade_type,
                    'payTypeID' => 50,
                    'mallID' => $args_data['mallID'],
                    'body' => '微商城',
                    'total_fee' => $args_data['money'],
                    'pcustID' => $pcustID,
                    'type' => 13,
                    'openId' => $openId,
                    'notify_url' => $notify_url
                ];

                $WxPayService = new WxPayService($params);

                $wx_pay = $WxPayService->request();
                if ($wx_pay['code'] == 200) {
                    $result_array['pay'] = $wx_pay['data'];
                }

            }

            if( $args_data['money'] == 0 ){

                //实例卡券服务类
                $service = new CardService();

                //发放卡券编号
                $grant_result = $service->grant( $card_data,$args_data['card_num'],$pcustID,$cust_info['custID'],false );

                if ( $grant_result['code'] != 200 ) {
                    throw new \Exception($grant_result['message'], $grant_result['code']);
                }

                CardCouponBuyLog::insert([
                    'uuid' => makeUuid(),
                    'timeStamp' => Carbon::now(),
                    'createTime' => Carbon::now(),
                    'creator' => $cust_info['custID'],
                    'bill_no' => $bill_no,
                    'pcustID' => $cust_info['pcustID'],
                    'card_id' => $card_data['card_id'],
                    'card_name' => $card_data['card_name'],
                    'card_type' => $card_data['card_type'],
                    'card_amount' => $args_data['card_num']
                ]);
            }else{

                $card_array = array(
                    'bill_no' => $bill_no,
                    'card_id' => $card_data['card_id'],
                    'pcustID' => $pcustID,
                    'custID' => $cust_info['custID'],
                    'card_name' => $card_data['card_name'],
                    'card_type' => $card_data['card_type'],
                    'card_amount' => $args_data['card_num']
                );

                //保存订单信息到redis
                Redis::set('card_'. $card_array['bill_no'], json_encode($card_array,true));

            }

            DB::commit();

            $result_array['card_id'] = $card_data['card_id'];

            return array('code' => 200, 'message' => 'ok', 'data' => $result_array);

        } catch (Exception $e) {

            DB::rollBack();

            if ($e->getCode() > 0) {
                return array('code' => $e->getCode(), 'message' => $e->getMessage());
            } else {
                error_log("=============卡券购买=============");
                error_log($e->getMessage());
                error_log("=============卡券购买=============");
                return array('code' => 500, 'message' => '系统错误');
            }
        }

    }
}